{% extends 'members/base.html' %}
{% set active_page = 'analytics' %}

{% block title %}数据分析{% endblock %}

{% block extra_css %}
<style>
/* 量表分析页面专用样式 */
.analytics-container {
    padding: 1rem;
}

.scale-selector {
    background: white;
    border-radius: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    padding: 2rem;
    margin-bottom: 2rem;
    border: 1px solid #f1f3f4;
}

.scale-card {
    border: 2px solid #e9ecef;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    background: white;
}

.scale-card:hover {
    border-color: #667eea;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
}

.scale-card.selected {
    border-color: #667eea;
    background: rgba(102, 126, 234, 0.05);
}

.scale-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: white;
    margin-right: 1rem;
}

.scale-stats {
    display: flex;
    gap: 2rem;
    margin-top: 1rem;
}

.scale-stat {
    text-align: center;
}

.scale-stat-number {
    font-size: 1.5rem;
    font-weight: bold;
    color: #667eea;
}

.scale-stat-label {
    font-size: 0.85rem;
    color: #6c757d;
}

.analysis-section {
    background: white;
    border-radius: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
    margin-bottom: 2rem;
    border: 1px solid #f1f3f4;
    display: none;
}

.analysis-section.active {
    display: block;
}

.section-header {
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
    padding: 1.5rem;
    border-radius: 15px 15px 0 0;
    border-bottom: 1px solid rgba(0,0,0,0.08);
}

.metric-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.metric-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    text-align: center;
    border: 1px solid #f1f3f4;
    transition: all 0.3s ease;
}

.metric-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.metric-value {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
}

.metric-value.primary { color: #667eea; }
.metric-value.success { color: #28a745; }
.metric-value.warning { color: #ffc107; }
.metric-value.danger { color: #dc3545; }

.chart-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.chart-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    border: 1px solid #f1f3f4;
    height: auto;
}

.chart-card canvas {
    max-height: 300px !important;
    height: 300px !important;
}

.empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: #6c757d;
}

.empty-state .icon {
    font-size: 4rem;
    color: #dee2e6;
    margin-bottom: 1rem;
}

.loading-state {
    text-align: center;
    padding: 3rem;
    color: #6c757d;
}

.loading-spinner {
    width: 3rem;
    height: 3rem;
    margin: 0 auto 1rem;
}

@media (max-width: 768px) {
    .scale-stats {
        flex-direction: column;
        gap: 1rem;
    }
    
    .chart-grid {
        grid-template-columns: 1fr;
    }
    
    .metric-cards {
        grid-template-columns: repeat(2, 1fr);
    }
}
</style>
{% endblock %}

{% block content %}
<div class="analytics-container">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1">数据分析</h2>
            <p class="text-muted mb-0">查看量表使用情况和数据统计</p>
        </div>
        <div>
            <button class="btn btn-outline-primary me-2" onclick="exportAnalytics()">
                <i class="bi bi-download me-1"></i>导出报告
            </button>
            <button class="btn btn-primary" onclick="refreshData()">
                <i class="bi bi-arrow-clockwise me-1"></i>刷新数据
            </button>
        </div>
    </div>

    <!-- 量表选择器 -->
    <div class="scale-selector">
        <h5 class="mb-3">选择量表查看分析</h5>
        <div id="scales-container">
            <div class="loading-state">
                <div class="spinner-border loading-spinner" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p>正在加载量表列表...</p>
            </div>
        </div>
    </div>

    <!-- 核心指标 -->
    <div id="metrics-section" class="analysis-section">
        <div class="section-header">
            <h5 class="mb-0">核心指标</h5>
        </div>
        <div class="p-3">
            <div class="metric-cards" id="metrics-cards">
                <!-- 指标卡片将通过JavaScript动态生成 -->
            </div>
        </div>
    </div>

    <!-- 图表分析 -->
    <div id="charts-section" class="analysis-section">
        <div class="section-header">
            <h5 class="mb-0">图表分析</h5>
        </div>
        <div class="p-3">
            <div class="chart-grid">
                <!-- 使用趋势图 -->
                <div class="chart-card">
                    <h6 class="mb-3">使用趋势</h6>
                    <canvas id="usageChart"></canvas>
                </div>
                
                <!-- 分数分布图 -->
                <div class="chart-card">
                    <h6 class="mb-3">分数分布</h6>
                    <canvas id="scoreChart"></canvas>
                </div>
                
                <!-- 完成率统计 -->
                <div class="chart-card">
                    <h6 class="mb-3">完成率统计</h6>
                    <canvas id="completionChart"></canvas>
                </div>
                
                <!-- 用户活跃度 -->
                <div class="chart-card">
                    <h6 class="mb-3">用户活跃度</h6>
                    <canvas id="activityChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 详细统计 -->
    <div id="details-section" class="analysis-section">
        <div class="section-header">
            <h5 class="mb-0">详细统计</h5>
        </div>
        <div class="p-3">
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">题目分析</h6>
                        </div>
                        <div class="card-body">
                            <div id="question-analysis">
                                <!-- 题目分析内容 -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">用户反馈</h6>
                        </div>
                        <div class="card-body">
                            <div id="user-feedback">
                                <!-- 用户反馈内容 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// 全局变量
let currentScaleId = null;
let charts = {};

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    loadMyScales();
});

// 加载我的量表
function loadMyScales() {
    apiRequest('/api/scales/my')
        .then(response => {
            if (response.success) {
                renderScales(response.data.scales);
            } else {
                showError('加载量表失败: ' + response.message);
            }
        })
        .catch(error => {
            console.error('加载量表失败:', error);
            showError('加载量表失败，请稍后重试');
        });
}

// 渲染量表列表
function renderScales(scales) {
    const container = document.getElementById('scales-container');
    
    if (!scales || scales.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-journal-text icon"></i>
                <p>您还没有创建任何量表</p>
                <button class="btn btn-primary" onclick="window.location.href='/members/scale-creator'">
                    <i class="bi bi-plus-circle me-1"></i>创建量表
                </button>
            </div>
        `;
        return;
    }
    
    let html = '';
    scales.forEach(scale => {
        const iconColor = getScaleIconColor(scale.category_name);
        html += `
            <div class="scale-card" onclick="selectScale(${scale.id})" data-scale-id="${scale.id}">
                <div class="d-flex align-items-center">
                    <div class="scale-icon" style="background: ${iconColor};">
                        <i class="bi bi-graph-up"></i>
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="mb-1">${escapeHtml(scale.title)}</h6>
                        <p class="text-muted mb-2">${escapeHtml(scale.description || '')}</p>
                        <div class="scale-stats">
                            <div class="scale-stat">
                                <div class="scale-stat-number">${scale.question_count || 0}</div>
                                <div class="scale-stat-label">题目数</div>
                            </div>
                            <div class="scale-stat">
                                <div class="scale-stat-number">${scale.usage_count || 0}</div>
                                <div class="scale-stat-label">使用次数</div>
                            </div>
                            <div class="scale-stat">
                                <div class="scale-stat-number">${getStatusText(scale.status)}</div>
                                <div class="scale-stat-label">状态</div>
                            </div>
                            <div class="scale-stat">
                                <div class="scale-stat-number">${formatDate(scale.created_at)}</div>
                                <div class="scale-stat-label">创建时间</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 选择量表
function selectScale(scaleId) {
    // 更新选中状态
    document.querySelectorAll('.scale-card').forEach(card => {
        card.classList.remove('selected');
    });
    document.querySelector(`[data-scale-id="${scaleId}"]`).classList.add('selected');
    
    currentScaleId = scaleId;
    
    // 显示分析区域
    document.querySelectorAll('.analysis-section').forEach(section => {
        section.classList.add('active');
    });
    
    // 加载分析数据
    loadAnalytics(scaleId);
}

// 加载分析数据
function loadAnalytics(scaleId) {
    // 检查用户是否已登录
    const userToken = localStorage.getItem('userToken');
    if (!userToken) {
        showError('请先登录后查看分析数据', true);
        return;
    }
    
    // 显示加载状态
    showLoading(true);
    
    apiRequest(`/api/scales/${scaleId}/analytics`)
    .then(response => {
        showLoading(false);
        if (response.success) {
            renderMetrics(response.data);
            renderCharts(response.data);
            renderDetails(response.data);
        } else {
            // 根据不同的错误状态码提供不同的错误信息
            let errorMessage = '加载分析数据失败';
            if (response.status === 403) {
                errorMessage = '您没有权限查看此量表的分析数据，只有量表创建者可以查看';
            } else if (response.status === 404) {
                errorMessage = '量表不存在或已被删除';
            } else if (response.status === 401) {
                errorMessage = '登录已过期，请重新登录';
            } else if (response.message) {
                errorMessage = response.message;
            }
            showError(errorMessage);
        }
    })
    .catch(error => {
        showLoading(false);
        console.error('加载分析数据失败:', error);
        
        // 提供更友好的错误信息
        let errorMessage = '加载分析数据失败，请稍后重试';
        if (error.message.includes('网络连接失败')) {
            errorMessage = '网络连接失败，请检查网络连接后重试';
        } else if (error.message.includes('Unauthorized')) {
            errorMessage = '登录已过期，请重新登录';
        }
        
        showError(errorMessage);
    });
}

// 渲染核心指标
function renderMetrics(data) {
    const container = document.getElementById('metrics-cards');
    
    const metrics = [
        {
            title: '总使用次数',
            value: data.total_assessments || 0,
            icon: 'bi-clipboard-data',
            color: 'primary'
        },
        {
            title: '完成次数',
            value: data.completed_assessments || 0,
            icon: 'bi-check-circle',
            color: 'success'
        },
        {
            title: '完成率',
            value: data.completion_rate ? `${data.completion_rate.toFixed(1)}%` : '0%',
            icon: 'bi-percent',
            color: 'warning'
        },
        {
            title: '平均分数',
            value: data.average_score ? data.average_score.toFixed(1) : '-',
            icon: 'bi-graph-up',
            color: 'primary'
        },
        {
            title: '活跃用户',
            value: data.active_users || 0,
            icon: 'bi-people',
            color: 'success'
        },
        {
            title: '本月使用',
            value: data.monthly_usage || 0,
            icon: 'bi-calendar-month',
            color: 'warning'
        }
    ];
    
    let html = '';
    metrics.forEach(metric => {
        html += `
            <div class="metric-card">
                <div class="metric-value ${metric.color}">${metric.value}</div>
                <div class="d-flex align-items-center justify-content-center">
                    <i class="${metric.icon} me-2"></i>
                    <span>${metric.title}</span>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 渲染图表
function renderCharts(data) {
    // 销毁现有图表
    Object.values(charts).forEach(chart => {
        if (chart) chart.destroy();
    });
    
    // 使用趋势图
    renderUsageChart(data.usage_trend || []);
    
    // 分数分布图
    renderScoreChart(data.score_distribution || []);
    
    // 完成率统计
    renderCompletionChart(data.completion_stats || {});
    
    // 用户活跃度
    renderActivityChart(data.activity_data || []);
}

// 使用趋势图
function renderUsageChart(trendData) {
    const ctx = document.getElementById('usageChart').getContext('2d');
    
    charts.usage = new Chart(ctx, {
        type: 'line',
        data: {
            labels: trendData.map(item => item.date) || [],
            datasets: [{
                label: '使用次数',
                data: trendData.map(item => item.count) || [],
                borderColor: '#667eea',
                backgroundColor: 'rgba(102, 126, 234, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 分数分布图
function renderScoreChart(scoreData) {
    const ctx = document.getElementById('scoreChart').getContext('2d');
    
    charts.score = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['0-20', '21-40', '41-60', '61-80', '81-100'],
            datasets: [{
                label: '人数',
                data: scoreData,
                backgroundColor: [
                    '#dc3545',
                    '#fd7e14',
                    '#ffc107',
                    '#28a745',
                    '#20c997'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 完成率统计
function renderCompletionChart(completionData) {
    const ctx = document.getElementById('completionChart').getContext('2d');
    
    charts.completion = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['已完成', '进行中', '已放弃'],
            datasets: [{
                data: [
                    completionData.completed || 0,
                    completionData.in_progress || 0,
                    completionData.abandoned || 0
                ],
                backgroundColor: [
                    '#28a745',
                    '#ffc107',
                    '#dc3545'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });
}

// 用户活跃度
function renderActivityChart(activityData) {
    const ctx = document.getElementById('activityChart').getContext('2d');
    
    charts.activity = new Chart(ctx, {
        type: 'radar',
        data: {
            labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
            datasets: [{
                label: '活跃度',
                data: activityData,
                borderColor: '#667eea',
                backgroundColor: 'rgba(102, 126, 234, 0.2)',
                pointBackgroundColor: '#667eea'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                r: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 渲染详细统计
function renderDetails(data) {
    renderQuestionAnalysis(data.question_stats || []);
    renderUserFeedback(data.feedback || []);
}

// 题目分析
function renderQuestionAnalysis(questionStats) {
    const container = document.getElementById('question-analysis');
    
    if (!questionStats || questionStats.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无题目分析数据</p>';
        return;
    }
    
    let html = '';
    questionStats.forEach((question, index) => {
        html += `
            <div class="mb-3">
                <div class="d-flex justify-content-between align-items-center">
                    <span class="fw-bold">题目 ${index + 1}</span>
                    <span class="badge bg-primary">${question.answer_rate}% 回答率</span>
                </div>
                <div class="progress mt-2" style="height: 8px;">
                    <div class="progress-bar" style="width: ${question.answer_rate}%"></div>
                </div>
                <small class="text-muted">平均用时: ${question.avg_time}秒</small>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 用户反馈
function renderUserFeedback(feedback) {
    const container = document.getElementById('user-feedback');
    
    if (!feedback || feedback.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无用户反馈</p>';
        return;
    }
    
    let html = '';
    feedback.slice(0, 5).forEach(item => {
        html += `
            <div class="mb-3 p-2 border rounded">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <small class="text-muted">用户 ${item.user_id}</small>
                    <small class="text-muted">${formatDate(item.created_at)}</small>
                </div>
                <p class="mb-0 small">${escapeHtml(item.content)}</p>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 刷新数据
function refreshData() {
    if (currentScaleId) {
        loadAnalytics(currentScaleId);
    } else {
        loadMyScales();
    }
}

// 导出分析报告
function exportAnalytics() {
    if (!currentScaleId) {
        alert('请先选择量表');
        return;
    }
    
    window.open(`/api/scales/${currentScaleId}/analytics/export`, '_blank');
}

// 工具函数
function getScaleIconColor(category) {
    const colors = {
        '心理健康': '#667eea',
        '人格测试': '#764ba2',
        '情绪评估': '#f093fb',
        '认知能力': '#4facfe',
        '行为评估': '#43e97b'
    };
    return colors[category] || '#6c757d';
}

function getStatusText(status) {
    const statusMap = {
        'DRAFT': '草稿',
        'PUBLISHED': '已发布',
        'ARCHIVED': '已归档'
    };
    return statusMap[status] || status;
}

function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showError(message, shouldRedirect = false) {
    const container = document.getElementById('scales-container');
    let html = `
        <div class="alert alert-danger" role="alert">
            <i class="bi bi-exclamation-triangle me-2"></i>${message}
    `;
    
    if (shouldRedirect) {
        html += `
            <div class="mt-3">
                <a href="{{ url_for('members.login') }}" class="btn btn-primary">
                    <i class="bi bi-box-arrow-in-right me-2"></i>立即登录
                </a>
            </div>
        `;
    }
    
    html += '</div>';
    container.innerHTML = html;
}

function showLoading(show = true) {
    const container = document.getElementById('scales-container');
    if (show) {
        container.innerHTML = `
            <div class="text-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <div class="mt-3">
                    <p class="text-muted">正在加载分析数据...</p>
                </div>
            </div>
        `;
    }
}

// API请求函数已在base.html中定义，无需重复定义
</script>
{% endblock %}